<?php

// 定义网站根目录.
define('ROOT_PATH', realpath(__DIR__ . '/../'));
// 定义网站应用目录.
define('APP_PATH', ROOT_PATH . '/App/');
// 定义网站缓存文件目录.
define('CACHE_PATH', ROOT_PATH . '/Caches/');

// 加载应用入口文件.
require_once APP_PATH . 'App.php';
App::autoload();

// 无限循环, 常驻内存
while (true) {

    // 如果24小时内未更新的商品, 过滤掉
    $minUptime = time() - 86400;
    $limit = 100;

    while (true) {
        $where = "`uptime` <= '$minUptime'";
        $sql = "select `product_id` from `product` where $where limit $limit";
        $datalist = \Db::instance()->getList($sql);

        if (!$datalist) {
            echo "clean product end\n";
            break;
        }

        foreach ($datalist as $d) {
            echo "delete product {$d['product_id']}\n";
            \Logic\Product::delete($d['product_id']);
        }
    }

    // 更新热卖清单
    $type = 'hot';
    // 默认最低红包2元
    $minPacket = 2;
    // 默认最低销量3333
    $minVolume = 3333;
    $where = "`red_packet` >= '$minPacket' and `volume` >= '$minVolume'";
    \Logic\Product::cacheProductList($type, $where, false, 'rand()');

    // 更新特别推荐
    $type = 'tui';
    // 默认最低红包2元
    $minPacket = 2;
    $where = "`status`= '2' and `red_packet` >= '$minPacket' and `amount` > 0";
    \Logic\Product::cacheProductList($type, $where, false, 'rand()');

    // 商城正品
    $type = 'mall';
    // 默认最低红包2元
    $minPacket = 2;
    $where = "`red_packet` >= '$minPacket' and `user_type`='1'";
    \Logic\Product::cacheProductList($type, $where, false, 'rand()');

    // 红包统计
    $dir = CACHE_PATH . 'tongji/';
    if (!file_exists($dir)) {
        mkdir($dir, 0777);
    }
    $row = \Db::instance()->getRow("select min(`packet_time`) as minDate, max(`packet_time`) as maxDate, sum(`total_packet`) as totalPacket from `myorder` where `packet_time` > 0 and `status`=6");
    file_put_contents($dir . 'tj.cache', json_encode($row));

    // 计算用户红包
    $monthTime = time() - 2592000; // 30天前时间戳
    $maxId = 0;

    while (true) {
        $where = "`id` > '$maxId'";
        $ulist = \Db::instance()->getList("select * from `wx_user` where $where order by `id` asc limit 20");

        if (!$ulist) {
            break;
        }

        foreach ($ulist as $u) {
            $openid = $u['openid'];
            $maxId = $u['id'];
            $allpacket = \Db::instance()->getSimple("select sum(`total_packet`) from `myorder` where `status`=6 and `packet_time` > 0 and `openid`='$openid'");
            $monpacket = \Db::instance()->getSimple("select sum(`total_packet`) from `myorder` where `status`=6 and `packet_time` >= '$monthTime'  and `openid`='$openid'");
            $allpacket = $allpacket ? $allpacket : 0;
            $monpacket = $monpacket ? $monpacket : 0;
            \Db::instance()->updateByWhere('wx_user', ['allpacket' => $allpacket, 'monpacket' => $monpacket], "`openid`='$openid'");
        }
    }

    $topAll = \Db::instance()->getList("select `id`,`openid`,`nickname`,`headimgurl`,`allpacket` as packet from `wx_user` where  `allpacket` > 0 order by `allpacket` desc limit 20");
    $topMon = \Db::instance()->getList("select `id`,`openid`,`nickname`,`headimgurl`,`monpacket` as packet from `wx_user` where `monpacket` > 0 order by `monpacket` desc limit 20");
    file_put_contents($dir . 'packetTopAll.cache', json_encode($topAll));
    file_put_contents($dir . 'packetTopMon.cache', json_encode($topMon));

    // 更新邀请红包
    $maxId = 0;
    while (true) {
        $where = "`id` > $maxId and `inviter` <> ''";
        $sql = "select distinct `inviter`, `id` from `wx_user` where $where group by `inviter` order by `id` asc limit 20";
        $ulist = \Db::instance()->getList($sql);
        if (!$ulist) {
            break;
        }

        foreach ($ulist as $u) {
            $maxId = $u['id'];
            $inviteid = $u['inviter'];

            $rs = \Db::instance()->getList("select `openid`,`allpacket` from `wx_user` where `inviter`='$inviteid'");
            foreach ($rs as $r) {
                $openid = $r['openid'];
                $allpacket = $r['allpacket'];
                $num = floor($allpacket / 100);

                if (!$num) {
                    continue;
                }

                if ($num > 10) {
                    $num = 10;
                }

                for ($i = 1; $i <= $num; $i++) {
                    $where = "`inviteid` = '$inviteid' && `openid`= '$openid' and `num`= '$i'";
                    if (\Db::instance()->count("select count(1) from `invite_packet` where $where")) {
                        continue;
                    }

                    $param = [
                        'inviteid' => $inviteid,
                        'openid' => $openid,
                        'num' => $i
                    ];

                    \Db::instance()->insert('invite_packet', $param);
                }
            }
        }
    }

    echo "end\n";
    // 休息30分钟
    sleep(1800);
}
